﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Scryber.Components;

namespace Scryber.Testing.AllSystemTests
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

            //Fill the repeater with all the pdfx documents in the App_Data/Samples folder.
            FileReference[] all = GetAllDocuments("App_Data\\Samples", "*.pdfx");
            this.FileList.DataSource = all;

            if (!this.IsPostBack)
                this.FileList.DataBind();
        }

        #region private FileReference[] GetAllDocuments(string folder, string ext)

        /// <summary>
        /// Fills a list with all the files in the specified folder (relative to this page) that match the required extension filter.
        /// </summary>
        /// <param name="folder"></param>
        /// <param name="ext"></param>
        /// <returns></returns>
        private FileReference[] GetAllDocuments(string folder, string ext)
        {
            string path = this.MapPath(this.Request.FilePath);
            path = System.IO.Path.GetDirectoryName(path);
            path = System.IO.Path.Combine(path, folder);

            string[] all = System.IO.Directory.GetFiles(path, ext);

            List<FileReference> matched = new List<FileReference>();
            foreach (string s in all)
            {
                string name = System.IO.Path.GetFileNameWithoutExtension(s);
                FileReference fr = new FileReference() { FileName = name, FullPath = s };
                matched.Add(fr);
            }

            return matched.ToArray();
        }

        #endregion

        /// <summary>
        /// Invoked from each link button on the repeater.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_GeneratePDF(object sender, CommandEventArgs e)
        {

            string path = e.CommandArgument.ToString();

            using (Scryber.Components.PDFDocument doc = Scryber.Components.PDFDocument.ParseDocument(path))
            {
                //These item and action events are required for some of the system tests.
                Scryber.Testing.AllSystemTests.CustomAssigments assign = new CustomAssigments();
                assign.AddItemAssigments(doc.Items);
                assign.ApplyCustomActions(doc);

                doc.ProcessDocument(this.Response);
            }
        }
    }

    /// <summary>
    /// Quick class that can be bound against for the repeater.
    /// </summary>
    public class FileReference
    {
        public string FileName { get; set; }
        public string FullPath { get; set; }

    }
}